<script setup lang="ts">
import {statusOpts} from "@/utils/status";
import {exportStat, StatShopData, statShopList, StatShopQuery} from "@/api/stat/shop";
import type {TableColumnCtx} from "element-plus";
import {getSupplierOptions} from "@/api/supplier";

defineOptions({
  name: "StatShop",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const objFormRef = ref(ElForm);

const loading = ref(false);
const total = ref(0);
const lastPage = ref(0);

const statusOptions = statusOpts();

const queryParams = reactive<StatShopQuery>({
  pageNum: 1,
  pageSize: 10,
});
const lists = ref<StatShopData[]>();
const shopList = ref<any[]>([]);
const current_role = localStorage.getItem("role_name");

const dialog = reactive({
  title: "",
  visible: false,
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  statShopList(queryParams)
    .then(({data}) => {
      lists.value = data.data || null;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

onMounted(() => {
  getSupplierOptions().then((data) => {
    shopList.value = data.data || [];
  })
  handleQuery();
});

interface SpanMethodProps {
  row: StatShopData;
  column: TableColumnCtx<StatShopData>;
  rowIndex: number;
  columnIndex: number;
}

const objectSpanMethod = ({row, column, rowIndex, columnIndex}: SpanMethodProps) => {
  if (columnIndex === 0) {
    if (row.isFirst) {
      return {
        rowspan: row.sameIndex,
        colspan: 1,
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      }
    }
  }
}

function bindExportStat() {
  queryParams.type = "shop";
  exportStat(queryParams || {}).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );

    const fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";
    const blob = new Blob([fileData], {type: fileType});
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form class="pull-left" ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="" prop="shop_id" style="width: 210px;" v-if="current_role == 'sys'">
          <el-select v-model="queryParams.shop_id" placeholder="请选择店铺" clearable>
            <el-option :label="op.title" v-for="op in shopList" :value="Number(op.id)"/>
          </el-select>
        </el-form-item>
        <el-form-item label="统计时间" prop="create_time" style="width: 420px;">
          <el-date-picker v-model="queryParams.create_time" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
                          range-separator="至"
                          start-placeholder="开始时间" end-placeholder="结束时间"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search/>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh/>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-button type="success" class="pull-right" @click="bindExportStat()">导出统计</el-button>
      <div class="clear"></div>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table ref="dataTableRef" v-loading="loading" :data="lists" border :span-method="objectSpanMethod">
        <el-table-column label="日期" prop="cdate"/>
        <el-table-column label="店铺" prop="shop_title"/>
        <el-table-column label="总交易额" prop="total_price"/>
        <el-table-column label="总单量" prop="amount"/>
        <el-table-column label="商品总金额" prop="product_price"/>
        <el-table-column label="总打包费" prop="bag_price"/>
        <el-table-column label="总配送费" prop="express_price"/>
      </el-table>
    </el-card>

  </div>
</template>
